﻿using Pay.DTO;
using Pay.IService;
using Pay.Token.Utils;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MvcExtension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Pay.Token.Controllers
{
    /// <summary>
    /// 用于接受微信公众号信息处理
    /// </summary>
    [RoutePrefix("WXPubAccount"), AllowAnonymous]
    public class WXPubAccountController : Controller
    {
        private IWXVerificationCodeService _iWXVerificationCodeService;
        private ISettingService _iSettingService;

        public WXPubAccountController(IWXVerificationCodeService iWXVerificationCodeService, ISettingService iSettingService)
        {
            _iWXVerificationCodeService = iWXVerificationCodeService;
            _iSettingService = iSettingService;
        }
        /// <summary>
        /// 接收到微信公众号消息
        /// </summary>
        /// <param name="postModel"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(PostModel postModel)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, t_RequestMethod.WX_PUB_APP_TOKEN))
            {
                return Content("参数错误！");
            }

            postModel.Token = t_RequestMethod.WX_PUB_APP_TOKEN;
            postModel.EncodingAESKey = t_RequestMethod.WX_PUB_APP_EncodingAESKey;//根据自己后台的设置保持一致
            postModel.AppId = t_RequestMethod.WX_PUB_APP_ID;//根据自己后台的设置保持一致

            var messageHandler = new WXPubMessageHandler(Request.InputStream, postModel, _iWXVerificationCodeService, _iSettingService, 10);//接收消息（第一步）

            messageHandler.Execute();//执行微信处理过程（第二步）

            return new WeixinResult(messageHandler);//返回（第三步）
        }


        /// <summary>
        /// 微信后台验证地址（使用Get），微信后台的“接口配置信息”的Url填写如：http://www.xxxx.com/WXPubAccount
        /// </summary>
        [HttpGet]
        [ActionName("Index")]
        public ActionResult Get(PostModel postModel, string echostr)
        {
            if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, t_RequestMethod.WX_PUB_APP_TOKEN))
            {
                return Content(echostr); //返回随机字符串则表示验证通过
            }
            else
            {
                return Content("failed:" + postModel.Signature + ","
                    + Senparc.Weixin.MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, t_RequestMethod.WX_PUB_APP_TOKEN) + "。" +
                    "如果你在浏览器中看到这句话，说明此地址可以被作为微信公众账号后台的Url，请注意保持Token一致。");
            }
        }


    }
}